const loki = require('lokijs');
import context from './context';

//数据库
var db;

//表:  刻印库、收藏、词条库、权重表、程序信息表、角色表、boss表、队伍表
var entries, favorites, affixs, weights, loads, appdatas,roles,boss,teams,weaps;
/*
    appdatas:  
    {
        name:
        value:
    }

    name:  data_update_version 当前使用的数据库版本(对应远端version.json)  如果version.json返回的日期大于本地日期 则需要更新数据库
    name:  data_last_version   本地更新日期(仅记录一下)
*/

/*
    entries：
    {
        id
        name 
        location
        affix1
        affix2
        type
        effect
        icon
    }
*/

/*
    affixs
    {
        id
        name
        type
        text
        value
        icon
        weight
    }
*/

/*
    favorites
    {
        id:
        name:String
        json:String  {
            mark:
            count:
            list:[
                {engr},{engr},{engr},{engr},{engr},{engr}
            ]
        }
    }
*/

/*
    weights
    {
        id:    default类id 0-1000  myself类1000起
        name:String  
        type:String    default不可删除 自带    myself玩家存的数据  
        data:object
    }
*/

/*
    loads
    {
        id:
        name: String 项目名 节奏榜、`角色名` 等
        type: String `项目名` 如  '角色' '排名' '攻略'  等待
        url:  String `攻略内容` 外联连接
    }
*/

let sql = {

    generateUUID() {
        var d = new Date().getTime();
        if (window.performance && typeof window.performance.now === "function") {
            d += performance.now(); //use high-precision timer if available
        }
        var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            var r = (d + Math.random() * 16) % 16 | 0;
            d = Math.floor(d / 16);
            return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
        });
        return uuid;
    },

    //初始化数据库
    initDbAndCollection() {
        // console.log("initDbAndCollection context=", context);
        // console.log("initDbAndCollection context.config=", context.config);

        db = new loki('mydata.db', {
            autoload: true,
            autosave: true,
            autosaveInterval: context.config.autosaveInterval,
            persistenceMethod: "fs",//localStorage
            autoloadCallback() {
                console.log("创建了数据库")

                entries = db.getCollection("entries");
                if (entries === null) {
                    console.log("新建engrs库")
                    entries = db.addCollection("entries", {
                        unique: ['id'],
                    });
                }

                favorites = db.getCollection("favorites");
                if (favorites === null) {
                    console.log("新建favorites库")
                    favorites = db.addCollection("favorites", {
                        indices: ['id'],
                    });
                    favorites.ensureUniqueIndex('id');
                }

                affixs = db.getCollection("affixs");
                if (affixs === null) {
                    console.log("新建affixs库")
                    affixs = db.addCollection("affixs");
                }

                weights = db.getCollection('weights');
                if (weights == null) {
                    console.log("新建weights库")
                    weights = db.addCollection("weights");
                }

                loads = db.getCollection('loads');
                if (loads == null) {
                    console.log("新建loads库")
                    loads = db.addCollection("loads");
                }

                appdatas = db.getCollection('appdatas');
                if (appdatas == null) {
                    console.log("新建appdatass库")
                    appdatas = db.addCollection("appdatas");
                    /*一些初始化数据*/
                }

                roles = db.getCollection('roles');
                if (roles == null) {
                    console.log("新建roles库")
                    roles = db.addCollection("roles");
                }

                boss = db.getCollection('boss');
                if (boss == null) {
                    console.log("新建boss库")
                    boss = db.addCollection("boss");
                }

                teams = db.getCollection('teams');
                if (teams == null) {
                    console.log("新建teams库")
                    teams = db.addCollection("teams");
                }

                weaps = db.getCollection('weaps');
                if (weaps == null) {
                    console.log("新建weaps库")
                    weaps = db.addCollection("weaps");
                }

                console.log("初始化数据库结束");
            },
        });
    },

    //删除所有数据
    clearDatabase(){
        db.collections.forEach(collection=>{
            collection.findAndRemove()
            console.log("已清除collection",collection.name)
        })
    },

    getCurrentData() {
        let now = new Date()
        let nowStr = now.getFullYear() + "-"
            + (now.getMonth() + 1 < 10 ? "0" + (now.getMonth() + 1) : now.getMonth() + 1) + "-"
            + (now.getDate() < 10 ? "0" + now.getDate() : now.getDate())
        // + " "
        // + (now.getHours() < 10 ? "0" + now.getHours() : now.getHours()) + ":"
        // + (now.getMinutes() < 10 ? "0" + now.getMinutes() : now.getMinutes())
        return nowStr;
    },

    queryVersion() {
        // console.log('appdatas',appdatas);
        let sqlrs = appdatas.find({
            'name': {
                '$eq': 'data_update_version'
            }
        });

        // console.log("sql.queryVersion", sqlrs);
        return sqlrs[0];
    },

    updateAppdatasByName(data) {
        let rs = appdatas.find({
            'name': data.name
        })[0];

        if (rs) {
            rs.value = data.value;
            appdatas.update(rs);
        } else {
            appdatas.insert(data);
        }

        // console.log('更新结果',appdatas.find({
        //     'name':data.name
        // }))
    },

    initUpdateEngrs(datas) {
        let collection = entries
        collection.chain().find().remove();

        let id = 0;
        datas.forEach(e => {
            e.id = id++;
            collection.insert(e);
        })

        let count = collection.count();
        console.log("更新了" + collection.name + "库,共" + count + "条数据");
    },

    initUpdateAffixs(datas) {
        let collection = affixs;
        collection.chain().find().remove();

        let id = 0;
        datas.forEach(e => {
            e.id = id++;
            collection.insert(e);
        })

        let count = collection.count();
        console.log("更新了" + collection.name + "库,共" + count + "条数据");
    },

    initUpdateWeights(datas) {
        let collection = weights;
        collection.chain().find({'type': { "$aeq": "default" }}).remove(); //仅删除默认配置
        
        datas = JSON.parse(JSON.stringify(datas));
        let id = 0;
        datas.forEach((e, index) => {
            e.id = e.id || "" + id++;
            collection.insert(e);
        });

        let count = collection.count();
        console.log("更新了" + collection.name + "库,共" + count + "条数据");
    },

    initUpdateLoads(datas) {
        let collection = loads;
        collection.chain().find().remove();

        let id = 0;
        datas.forEach(e => {
            e.id = id++;
            collection.insert(e);
        });

        let count = collection.count();
        console.log("更新了" + collection.name + "库,共" + count + "条数据");
    },

    initUpdateRoles(datas){
        let collection = roles;
        collection.chain().find().remove();

        datas.forEach(e => {
            collection.insert(e);
        });

        let count = collection.count();
        console.log("更新了" + collection.name + "库,共" + count + "条数据");
    },

    initUpdateBoss(datas){
        let collection = boss;
        collection.chain().find().remove();

        datas.forEach(e => {
            collection.insert(e);
        });

        let count = collection.count();
        console.log("更新了" + collection.name + "库,共" + count + "条数据");
    },

    initUpdateWeaps(datas){
        let collection = weaps;
        collection.chain().find().remove();

        datas.forEach(e => {
            collection.insert(e);
        });

        let count = collection.count();
        console.log("更新了" + collection.name + "库,共" + count + "条数据");
    },

    queryAllEngrNames() {
        return entries.find({
            'location': 1
        });
    },

    queryAllAffixs() {
        return affixs.data;
    },

    queryEngr(name, loc, param, res) {

        let conditions = {};

        if (name && name != "") {
            conditions['name'] = {
                '$aeq': name
            }
        }

        if (loc!=null && loc != "") {
            conditions['location'] = {
                '$aeq': loc
            }
        }

        if (param && param != "") {
            conditions['type'] = {
                '$aeq': param
            }
        }

        if (res && res != "") {
            conditions['type'] = {
                '$aeq': res
            }
        }

        console.log("查询条件:", conditions);
        let sqlrs = entries.find(conditions);
        return sqlrs;
    },

    queryEngrById(id) {
        let sqlrs = entries.find({
            "id": {
                "$aeq": id
            }
        });

        if (!sqlrs[0]) {
            console.log("sql.queryEngrById", '未找到', id);
        }
        return sqlrs[0];
    },

    insertFavorited(data) {
        favorites.insert(data);
    },

    removeFavoritedById(id) {
        let sqlrs = favorites.find({
            "id": {
                "$aeq": id
            }
        });

        if (sqlrs[0]) {
            favorites.remove(sqlrs[0]);
            return true;
        }

        return false;
    },

    clearFavorited(){
        favorites.chain().find().remove();
    },

    queryAllFavorited() {
        return favorites.find();
    },

    insertWeights(data) {
        data.id = sql.generateUUID();
        data.data = JSON.stringify(data.data);
        weights.insert(data);
        console.log("sql.js", "insertWeights", data);
    },

    queryAllWeightsName() {
        return weights.find();
    },

    queryWeightsById(id) {
        let sqlrs = weights.find({
            "id": {
                "$aeq": id
            }
        })[0]

        if (sqlrs) {
            //拷贝一个克隆
            let object = JSON.parse(JSON.stringify(sqlrs));
            object.data = JSON.parse(object.data);
            delete object.$loki;
            delete object.meta;
            return object;
        }
    },

    removeCustomWeights(){
        let sqlrs = weights.find({
            "type" :{
                "$aeq": "custom"
            }
        })

        sqlrs && sqlrs.map(e=>{
            weights.remove(e);
        })
    },

    queryAllRoles(){
        return roles.find();
    },

    queryAllBoss(){
        return boss.find();
    },

    queryAllTeams(){
        return teams.find();
    },

    queryTeamsById(id){
        let sqlrs = teams.find({
            "id": {
                "$aeq": id
            }
        })

        if(sqlrs[0]){
            let rs = JSON.parse(JSON.stringify(sqlrs[0]));
            delete rs.$loki;
            delete rs.meta;
            return rs;
        }else{
            return null;
        }
    },

    insertTeams(data){
        teams.insert(data);
    },

    removeTeamsById(id){
        let sqlrs = teams.find({
            "id": {
                "$aeq": id
            }
        })

        if(sqlrs[0]){
            teams.remove(sqlrs[0]);
            return true;
        }

        return false;
    },

    queryAllWeaps(){
        let sqlrs = weaps.find();
        
        if(sqlrs){
            let rs = JSON.parse(JSON.stringify(sqlrs));
            delete rs.$loki;
            delete rs.meta;
            return rs;
        }else{
            return null;
        }
    }
}

export default sql;